package com.dries.security.core.social.qq.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.dries.security.common.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/9/15 15:46
 */
@Slf4j
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {

    private static final String QQ_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";
    private static final String QQ_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    private final String appId;
    private final String openId;

    public QQImpl(String accessToken, String appId){
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);

        this.appId = appId;

        String url = String.format(QQ_GET_OPENID, accessToken);
        String result = getRestTemplate().getForObject(url, String.class);

        log.info("获取用户QQ的openId===》{}", result);
        openId = StrUtil.subBetween(result,"\"openid\":\"","\"}");

    }

    @Override
    public QQUserInfo getUserInfo() {

        QQUserInfo userInfo = null;

        String url = String.format(QQ_GET_USERINFO, appId, openId);
        String result = getRestTemplate().getForObject(url,String.class);

        try {
            userInfo = JSONUtil.toBean(result, QQUserInfo.class);
            userInfo.setOpenId(openId);
            return userInfo;
        } catch (Exception e) {
            throw new ApiException("获取用户信息失败！", e);
        }
    }
}
